package mycoffee.order.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class ImageManager implements Runnable {

	String imageURL;
	String folderPath;
	String fileName;
	Thread myThread;

	public void DownloadFromUrl(String aImageURL, String aFolderPath ,String aFileName) {
		this.imageURL = aImageURL;
		this.folderPath = aFolderPath;
		this.fileName = aFileName;
		myThread = new Thread(this); 
	    myThread.start();
	}

	private void request() {
		Log.d("In::DownloadFromUrl","imageURL = " + imageURL + ",filename = " + fileName);
		String url = "http://mycoffee-v02.tt-tech.vn/" + imageURL;
		try {
		        InputStream in = new URL(url).openConnection().getInputStream();
		        Bitmap bm = BitmapFactory.decodeStream(in);
		        File dir = new File(folderPath);

		        if(!dir.exists()) {
		        	dir.mkdirs();
		        }

		        File fileUri = new File(folderPath, fileName);
		        FileOutputStream outStream = null;
		        outStream = new FileOutputStream(fileUri);
		        bm.compress(Bitmap.CompressFormat.PNG, 75, outStream);
		        outStream.flush();
		        outStream.close();

		} catch (IOException e) {
		        Log.d("ImageManager", "Error: " + e);
		}
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		request();
	}
}
